﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using WatiN.Core;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace EasyOpenLink
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        List<string> mylinklist = new List<string>();
        public Form1()
        {
            InitializeComponent(); 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox1.Text == null)
            {
                MessageBox.Show("There is no link to check!", "Notification");
            }
            else
            {
                string url = textBox1.Text;
                listView1.Items.Clear();
                FillLinksToGrid(url);
            }
        }

        public void FillLinksToGrid(string url)
        {
            MatchCollection mc = GetSingleURLLinks(url);
            int count = 1;

            if (mc != null && mc.Count != 0)
            {
                foreach (Match match in mc)
                {
                    ListViewItem item = new ListViewItem();

                    if (!match.Value.Contains("#") && match.Groups["url"].Value != "")
                    {
                        item.SubItems[0].Text = count.ToString();
                        if (!match.Groups["url"].Value.StartsWith("http://") && !match.Groups["url"].Value.StartsWith("/"))
                        {
                            if (url.EndsWith("/"))
                            {
                                string fullLink = url + match.Groups["url"].Value;
                                item.SubItems.Add(fullLink);
                                item.SubItems.Add(match.Groups["text"].Value);
                                mylinklist.Add(fullLink);
                            }
                            else
                            {
                                string fullLink = url + "/" + match.Groups["url"].Value;
                                item.SubItems.Add(fullLink);
                                item.SubItems.Add(match.Groups["text"].Value);
                                mylinklist.Add(fullLink);
                            }
                        }
                        else if (!match.Groups["url"].Value.StartsWith("http://") && match.Groups["url"].Value.StartsWith("/"))
                        {
                            string fullLink = url.Substring(0, url.IndexOf(".com") + 4) + match.Groups["url"].Value;
                            item.SubItems.Add(fullLink);
                            item.SubItems.Add(match.Groups["text"].Value);
                            mylinklist.Add(fullLink);
                        }
                        else
                        {
                            item.SubItems.Add(match.Groups["url"].Value);
                            item.SubItems.Add(match.Groups["text"].Value);
                            mylinklist.Add(match.Groups["url"].Value);
                        }
                        this.listView1.Invoke((Action)delegate() { listView1.Items.Add(item); });
                        count++;

                        //this.label1.Invoke((Action)delegate() { label1.Text = Convert.ToInt32(count++).ToString(); });
                    }
                }
            }
            else
            {
                MessageBox.Show("There is no link", "Notification");
            }
        }
        public MatchCollection GetSingleURLLinks(string url)
        {
            try
            {
                WebClient wc = new WebClient();
                string result = wc.DownloadString(url);
                string xixi = @"(?i)<a(?>(?:(?!href=)[^>])*)href=(['""]?)(?<url>[^""'\s>]*)\1[^>]*>(?<text>[\s\S]*?)</a>";
                // string haha = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
                MatchCollection mc = Regex.Matches(result, xixi, RegexOptions.IgnoreCase);
                return mc;
            }
            catch
            {
                return null;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            BrowserDriver br = new BrowserDriver();
            string foldName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
            Directory.CreateDirectory(foldName);
            int fileCount = 1;
            foreach (string url in mylinklist)
            {
                if (BrowserDriver.ActiveBrowser == null)
                {
                    br.Invoke(BrowserType.InternetExplorer);
                    br.NavigateTo(url);
                    br.CaptureWebPage(foldName + "/" + fileCount.ToString() + ".jpg");
                    br.SendKeys("^{t}");
                    fileCount++;
                }
                else
                {     
                    try
                    {
                        BrowserDriver.ActiveBrowser.BringToFront();
                        if (IE.AttachTo<IE>(Find.ByTitle("")) == null)
                        {
                            br.SendKeys("^{t}");
                        }
                        IE ie = IE.AttachTo<IE>(Find.ByTitle(""));
                        
                        ie.GoTo(url);         
                        ie.CaptureWebPageToFile(foldName + "/" + fileCount.ToString() + ".jpg");
                        ie = null;
                    }
                    catch (WatiN.Core.Exceptions.BrowserNotFoundException ex)
                    {
                        BrowserDriver.ActiveBrowser.BringToFront();
                        br.SendKeys("^{t}");
                        IE ie = IE.AttachTo<IE>(Find.ByTitle(""));
                        ie.GoTo(url);
                        ie.CaptureWebPageToFile(foldName + "/" + fileCount.ToString() + ".jpg");
                        ie = null;
                    }
                    Thread.Sleep(500);
                    br.SendKeys("^{t}");
                    fileCount++;

                }
            }
        }

        public void CloseAllIEWindows()
        {
            try
            {
                BrowserDriver.ActiveBrowser = null;
                var ieProcesses = Process.GetProcessesByName("iexplore");
                foreach (var p in ieProcesses)
                {
                    p.Kill();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "TXT Files(*.txt)|*.txt";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.FilterIndex = 1;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                
                FileStream fs = File.Open(fileName, FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                mylinklist.Clear();
                string str = sr.ReadLine();
                mylinklist.Add(str);

                while (str != null)  
                {           
                   str = sr.ReadLine();
                   if (str != null && str != "")
                   {
                       mylinklist.Add(str);
                   }
                }  
                sr.Close();  
                fs.Close();
                if (mylinklist.Count > 0)
                {
                    listView1.Items.Clear();
                    int count = 1;
                    foreach (string link in mylinklist)
                    {
                        ListViewItem item = new ListViewItem();
                        item.SubItems[0].Text = count.ToString();
                        item.SubItems.Add(link);
                        listView1.Items.Add(item);
                        count++;
                    }
                }
            }
        }
    }
}
